package org.xtown.bingluo.xtieba.ui.activities;

import java.util.ArrayList;
import java.util.List;

import org.xtown.bingluo.xtieba.R;
import org.xtown.bingluo.xtieba.components.CustomWebView;
import org.xtown.bingluo.xtieba.db.XtiebaPostsDb;
import org.xtown.bingluo.xtieba.db.XtiebaPostsInfoDb;
import org.xtown.bingluo.xtieba.model.adapters.PostsCursorAdapter;
import org.xtown.bingluo.xtieba.standby.Constants;
import org.xtown.bingluo.xtieba.utils.ApplicationUtils;
import org.xtown.bingluo.xtieba.utils.LogUtlils;
import org.xtown.bingluo.xtieba.utils.StringUtils;
import org.xtown.bingluo.xtieba.utils.UiUtils;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends BaseActivity {

	public static MainActivity INSTANCE = null;

	public static final int CRAWL_ACTIVITY_REQUESTCODE = 100;
	public static final int SETTING_ACTIVITY_REQUESTCODE = 101;
	public static final int POSTS_INFO_ACTIVITY_REQUESTCODE = 102;

	private static final int MENU_PERSONAL_INFORMATION = Menu.FIRST;
	private static final int MENU_CLEAR_ALL = Menu.FIRST + 1;
	private static final int MENU_FEEDBACK = Menu.FIRST + 2;
	private static final int MENU_SPIDER = Menu.FIRST + 3;
	private static final int MENU_SETTING = Menu.FIRST + 4;
	private static final int MENU_EXIT = Menu.FIRST + 5;
	private static final int MENU_HELP = Menu.FIRST + 6;

	private static final int CONTEXT_MENU_GOTO_CRAWLACTIVITY = Menu.FIRST + 10;
	private static final int CONTEXT_MENU_DELETE = Menu.FIRST + 11;
	private static final int CONTEXT_MENU_DOWNLOAD = Menu.FIRST + 12;
	private static final int CONTEXT_MENU_COPY = Menu.FIRST + 13;
	private static final int CONTEXT_MENU_SEND_MAIL = Menu.FIRST + 14;
	private static final int CONTEXT_MENU_SHARE = Menu.FIRST + 15;
	private static final int CONTEXT_MENU_ONLINE_VIEW = Menu.FIRST + 16;

	protected ProgressDialog mProgressDialog;

	protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(
			ViewGroup.LayoutParams.FILL_PARENT,
			ViewGroup.LayoutParams.FILL_PARENT);

	protected static final int FILL_PAGINGLISTVIEWDATA = 110;

	protected LayoutInflater mInflater = null;

	private List<CustomWebView> mWebViews;

	private Button ToCrawlActivityBtn;
	private ListView lvPosts;

	private PostsCursorAdapter mPagingListViewDataCursorAdapter;

	private Cursor mCursor;

	private Spinner mPageNumSpinner;

	private int postsCount;

	private int currentPageNum = 0;

	private Button PrePage;

	private Button NextPage;

	protected Intent onCreateContextMenuIntent = null;

	private int pageTotalNum;

	protected int currentOffet = 0;

	private enum SwitchUpdateUiCommand {
		INIT, RESET, CHANGE_PAGE, CHANGE_PAGE_CONTENT,
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		INSTANCE = this;
		setProgressBarVisibility(true);
		setContentView(R.layout.main);
		// mCircularProgress = getResources().getDrawable(R.drawable.spinner);
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		initData();
		buildComponents();
		updateSwitchTabsMethod();
		// mViewFlipper.removeAllViews();
		
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MENU_CLEAR_ALL:
				Boolean r = (Boolean) msg.obj;
				if (r) {
					UiUtils.getInstance(INSTANCE).CreateShowToast(
							R.string.ClearAllSuccess, Toast.LENGTH_SHORT);
				} else {
					UiUtils.getInstance(INSTANCE).CreateShowToast(
							R.string.ClearAllFailure, Toast.LENGTH_SHORT);
				}
				mCursor = null;
				getPagingListViewData(currentOffet, Constants.PAGE_SIZE, SwitchUpdateUiCommand.RESET);
				if (mProgressDialog != null && mProgressDialog.isShowing()) {
					mProgressDialog.cancel();
				}
				break;
			case CONTEXT_MENU_DELETE:
				Object[] obj = (Object[]) msg.obj;
				Boolean r2 = (Boolean) obj[0];
				if (r2) {
					UiUtils.getInstance(INSTANCE).CreateShowToast(
							R.string.deleteSuccess, Toast.LENGTH_SHORT);
				} else {
					UiUtils.getInstance(INSTANCE).CreateShowToast(
							R.string.deleteFailure, Toast.LENGTH_SHORT);
				}
				getPagingListViewData(currentOffet, Constants.PAGE_SIZE, SwitchUpdateUiCommand.RESET);
//				updateUI(SwitchUpdateUiCommand.RESET);
				if (mProgressDialog != null && mProgressDialog.isShowing()) {
					mProgressDialog.cancel();
				}
				break;
			case FILL_PAGINGLISTVIEWDATA:
				Boolean r3 = (Boolean) msg.obj;
				updateUI(currentSwitchUpdateUiCommand);
				lvPosts.setVisibility(View.VISIBLE);
				loadingTips.setVisibility(View.GONE);
				break;
			}
		}
	};

	private void initData() {

	}

	private TextView loadingTips;

	private SwitchUpdateUiCommand currentSwitchUpdateUiCommand;

	private TextView postsTips;

	private EditText toOnlineWhatPageEdit;

	/**
	 * Apply preferences to the current UI objects.
	 */
	public void applyPreferences() {
		// To update to Bubble position.
		setToolbarsVisibility(false);

		updateSwitchTabsMethod();

		for (CustomWebView view : mWebViews) {
			view.initializeOptions();
		}
	}

	private void getPagingListViewData(final int offet, final int length,
			SwitchUpdateUiCommand command) {
		currentSwitchUpdateUiCommand = command;
		lvPosts.setVisibility(View.GONE);
		loadingTips.setVisibility(View.VISIBLE);
		loadingTips.setText(R.string.loading);
		new Thread() {
			public void run() {
				Boolean r = true;
				postsCount = XtiebaPostsDb.getNetInstance(INSTANCE).getCount();
				LogUtlils.println("postsCount==" + postsCount);
				pageTotalNum = (int) Math.ceil((postsCount * 1.0)
						/ Constants.PAGE_SIZE);
				LogUtlils.println("pageTotalNum==" + pageTotalNum);
				mCursor = XtiebaPostsDb.getNetInstance(INSTANCE).getListCursor(
						offet, length);
				Message msg = handler.obtainMessage();
				msg.what = FILL_PAGINGLISTVIEWDATA;
				msg.obj = r;
				handler.sendMessage(msg);
			};
		}.start();
	}

	/**
	 * Change the tool bars visibility.
	 * 
	 * @param visible
	 *            If True, the tool bars will be shown.
	 */
	private void setToolbarsVisibility(boolean visible) {

	}

	private void updateSwitchTabsMethod() {
		String method = PreferenceManager.getDefaultSharedPreferences(this)
				.getString(Constants.PREFERENCES_GENERAL_SWITCH_TABS_METHOD,
						"buttons");

		if (method.equals("buttons")) {
		} else if (method.equals("fling")) {
		} else if (method.equals("both")) {
		} else {
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {

		case CRAWL_ACTIVITY_REQUESTCODE:
			getPagingListViewData(currentOffet, Constants.PAGE_SIZE,
					SwitchUpdateUiCommand.RESET);
			break;
		case SETTING_ACTIVITY_REQUESTCODE:
			getPagingListViewData(currentOffet, Constants.PAGE_SIZE,
					SwitchUpdateUiCommand.RESET);
			break;
		case POSTS_INFO_ACTIVITY_REQUESTCODE:
			getPagingListViewData(currentOffet, Constants.PAGE_SIZE,
					SwitchUpdateUiCommand.RESET);
			break;
		default:
			break;
		}
	}

	/**
	 * Create main UI.
	 */
	private void buildComponents() {

//		mProgressDialog = new ProgressDialog((Context) INSTANCE);
		mWebViews = new ArrayList<CustomWebView>();

		ToCrawlActivityBtn = (Button) findViewById(R.id.ToCrawlActivityBtn);
		ToCrawlActivityBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intent = new Intent(INSTANCE, CrawlActivity.class);
				INSTANCE.startActivityForResult(intent,
						CRAWL_ACTIVITY_REQUESTCODE);
			}
		});
		ToCrawlActivityBtn.setVisibility(View.GONE);

		postsTips = (TextView) findViewById(R.id.postsTips);
		loadingTips = (TextView) findViewById(R.id.loadingTips);
		lvPosts = (ListView) findViewById(R.id.posts);
		initListView();

		mPageNumSpinner = (Spinner) findViewById(R.id.PageNumSpinner);
		PrePage = (Button) findViewById(R.id.PrePage);
		PrePage.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				int postsCountPageNum = pageTotalNum - 1;
				if (currentPageNum == 0) {
					currentPageNum = postsCountPageNum;
				} else {
					currentPageNum--;
				}
				currentOffet = currentPageNum * Constants.PAGE_SIZE;
				getPagingListViewData(currentOffet, Constants.PAGE_SIZE,
						SwitchUpdateUiCommand.CHANGE_PAGE);
			}
		});
		NextPage = (Button) findViewById(R.id.NextPage);
		NextPage.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				int postsCountPageNum = pageTotalNum - 1;
				if (currentPageNum == postsCountPageNum) {
					currentPageNum = 0;
				} else {
					currentPageNum++;
				}
				currentOffet = currentPageNum * Constants.PAGE_SIZE;
				getPagingListViewData(currentOffet, Constants.PAGE_SIZE,
						SwitchUpdateUiCommand.CHANGE_PAGE);
			}
		});
	}

	private void initListView() {

		/* Add Context-Menu listener to the ListView. */
		lvPosts.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

			public void onCreateContextMenu(ContextMenu cttMenu, View view,
					ContextMenuInfo info) {
				cttMenu.clearHeader();
				cttMenu.add(0, CONTEXT_MENU_GOTO_CRAWLACTIVITY, 0,
						R.string.Main_GoToCrawlActivity);
				cttMenu.add(0, CONTEXT_MENU_ONLINE_VIEW, 0, R.string.online_view);
				cttMenu.add(0, CONTEXT_MENU_DELETE, 0, R.string.delete);
			}
		});

		lvPosts.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				LogUtlils.println("onItemClick?");
				String kzid = (String) view.getTag();
				onCreateContextMenuIntent = new Intent();
				onCreateContextMenuIntent.setClass(INSTANCE,
						PostsInfoActivity.class);
				onCreateContextMenuIntent.putExtra(XtiebaPostsDb.KZID, kzid);
				if (onCreateContextMenuIntent != null) {
					INSTANCE.startActivityForResult(onCreateContextMenuIntent,
							POSTS_INFO_ACTIVITY_REQUESTCODE);
				}
			}
		});
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case CONTEXT_MENU_GOTO_CRAWLACTIVITY:
			LogUtlils.println("onContextItemSelected?");
			String kzid = (String) menuInfo.targetView.getTag();
			onCreateContextMenuIntent = new Intent();
			onCreateContextMenuIntent.setClass(INSTANCE, CrawlActivity.class);
			onCreateContextMenuIntent.putExtra("kzid", kzid);
			if (onCreateContextMenuIntent != null) {
				INSTANCE.startActivityForResult(onCreateContextMenuIntent,
						CRAWL_ACTIVITY_REQUESTCODE);
			}
			return true;
		case CONTEXT_MENU_ONLINE_VIEW:
			final Builder builder = new AlertDialog.Builder(INSTANCE).setIcon(
		    R.drawable.icon).setTitle(R.string.Commons_Ask).setMessage(R.string.Commons_WhatFloor).setPositiveButton(R.string.Commons_Ok,
		    new DialogInterface.OnClickListener() {
		     @Override
		     public void onClick(DialogInterface arg0, int arg1) {
		    	 String kzid = (String) menuInfo.targetView.getTag();
		    	 String pn = toOnlineWhatPageEdit.getText().toString();
		    	 if (StringUtils.isNumeric(pn)) {
		    		 String url = String.format(Constants.ONLINE_URL_TEMPLATE, kzid, pn);
		    		 LogUtlils.println("url==="+url);
		    		 if (!ApplicationUtils.openView(INSTANCE, Uri.parse(url), "text/html", "com.android.browser", "com.android.browser.BrowserActivity")) {
		    			 UiUtils.getInstance(INSTANCE).CreateShowToast(
									R.string.Commons_OpenError, Toast.LENGTH_SHORT);
		    		 }
		    	 } else {
		    		 UiUtils.getInstance(INSTANCE).CreateShowToast(
								R.string.Commons_PleaseEnterNumber, Toast.LENGTH_SHORT);
		    	 }
		     }
		    });
			toOnlineWhatPageEdit = new EditText(INSTANCE);
			toOnlineWhatPageEdit.setHint(R.string.Commons_PleaseEnterNumber);
			toOnlineWhatPageEdit.setHintTextColor(R.color.et_text_1);
			toOnlineWhatPageEdit.setInputType(InputType.TYPE_CLASS_NUMBER);
			toOnlineWhatPageEdit.setSingleLine(true);
			toOnlineWhatPageEdit.setText("1");
			toOnlineWhatPageEdit.selectAll();
			toOnlineWhatPageEdit.setSelected(true);
		    builder.setView(toOnlineWhatPageEdit);
		    builder.show();
			return true;
		case CONTEXT_MENU_DELETE:
			DialogInterface.OnClickListener onYes = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					mProgressDialog = new ProgressDialog((Context) INSTANCE);
					mProgressDialog.setIndeterminate(true);
					mProgressDialog.setTitle(R.string.Execution);
					mProgressDialog.setMessage(getString(R.string.Execution));
					mProgressDialog.setCancelable(false);
					mProgressDialog.show();
					final String kzid2 = (String) menuInfo.targetView.getTag();
					new Thread() {
						public void run() {
							Boolean r = true;
							int postsId = XtiebaPostsDb
									.getNetInstance(INSTANCE).deleteByKzid(
											kzid2);
							XtiebaPostsInfoDb.getNetInstance(INSTANCE)
									.deleteByPostsId(postsId);
							mCursor = XtiebaPostsDb.getNetInstance(INSTANCE)
									.getListCursor(currentOffet,
											Constants.PAGE_SIZE);
							Message msg = handler.obtainMessage();
							msg.what = CONTEXT_MENU_DELETE;
							msg.obj = new Object[] { r, menuInfo };
							handler.sendMessage(msg);
						};
					}.start();
				}
			};
			ApplicationUtils.showYesNoDialog(INSTANCE,
					android.R.drawable.ic_menu_help, R.string.Commons_Ask,
					R.string.IsSureClearThis, onYes);
			return true;
		}
		return false;
	}

	// 点击Menu时，系统调用当前Activity的onCreateOptionsMenu方法，并传一个实现了一个Menu接口的menu对象供你使用
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		/*
		 * add()方法的四个参数，依次是： 1、组别，如果不分组的话就写Menu.NONE,
		 * 2、Id，这个很重要，Android根据这个Id来确定不同的菜单 3、顺序，那个菜单现在在前面由这个参数的大小决定
		 * 4、文本，菜单的显示文本
		 */
		menu.add(Menu.NONE, MENU_HELP, 1, "帮助").setIcon(
				android.R.drawable.ic_menu_help);
		// setIcon()方法为菜单设置图标，这里使用的是系统自带的图标，同学们留意一下,以
		// android.R开头的资源是系统提供的，我们自己提供的资源是以R开头的
		menu.add(Menu.NONE, MENU_CLEAR_ALL, 2, "清空").setIcon(
				android.R.drawable.ic_menu_delete);
		menu.add(Menu.NONE, MENU_FEEDBACK, 3, "反馈").setIcon(
				android.R.drawable.ic_menu_add);
		menu.add(Menu.NONE, MENU_SPIDER, 4, "蜘蛛").setIcon(
				android.R.drawable.ic_menu_info_details);
		menu.add(Menu.NONE, MENU_SETTING, 5, "设置").setIcon(
				android.R.drawable.ic_menu_close_clear_cancel);
		menu.add(Menu.NONE, MENU_EXIT, 6, "退出").setIcon(
				android.R.drawable.ic_menu_close_clear_cancel);
		// return true才会起作用
		return true;

	}

	// 菜单项被选择事件
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_HELP:
			Toast.makeText(this, "帮助菜单被点击了", Toast.LENGTH_LONG).show();
			break;
		case MENU_CLEAR_ALL:
			// Toast.makeText(this, "清空菜单被点击了", Toast.LENGTH_LONG).show();
			DialogInterface.OnClickListener onYes = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					mProgressDialog = new ProgressDialog((Context) INSTANCE);
					mProgressDialog.setIndeterminate(true);
					mProgressDialog.setTitle(R.string.Execution);
					mProgressDialog.setMessage(getString(R.string.Execution));
					mProgressDialog.setCancelable(false);
					mProgressDialog.show();
					clearAllPosts(handler, MENU_CLEAR_ALL);
				}
			};
			ApplicationUtils.showYesNoDialog(INSTANCE,
					android.R.drawable.ic_menu_help, R.string.Commons_Ask,
					R.string.IsSureClearAll, onYes);
			break;
		case MENU_FEEDBACK:
			Toast.makeText(this, "反馈菜单被点击了", Toast.LENGTH_LONG).show();
			break;
		case MENU_SPIDER:
			// Toast.makeText(this, "蜘蛛菜单被点击了", Toast.LENGTH_LONG).show();
			Intent intent2 = new Intent(INSTANCE, CrawlActivity.class);
			INSTANCE.startActivityForResult(intent2, CRAWL_ACTIVITY_REQUESTCODE);
			break;
		case MENU_SETTING:
			// Toast.makeText(this, "设置菜单被点击了", Toast.LENGTH_LONG).show();
			Intent intent = new Intent();
			intent.setClass(INSTANCE, SettingActivity.class);
			startActivityForResult(intent, SETTING_ACTIVITY_REQUESTCODE);
			break;
		case MENU_EXIT:
			// Toast.makeText(this, "退出菜单被点击了", Toast.LENGTH_LONG).show();
			super.isExit();
			break;
		}

		return false;
	}

	// 选项菜单被关闭事件，菜单被关闭有三种情形，menu按钮被再次点击、back按钮被点击或者用户选择了某一个菜单项
	@Override
	public void onOptionsMenuClosed(Menu menu) {
		// Toast.makeText(this, "选项菜单关闭了", Toast.LENGTH_LONG).show();
	}

	// 菜单被显示之前的事件
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// Toast.makeText(this,
		// "选项菜单显示之前onPrepareOptionsMenu方法会被调用，你可以用此方法来根据打当时的情况调整菜单",
		// Toast.LENGTH_LONG).show();
		// 如果返回false，此方法就把用户点击menu的动作给消费了，onCreateOptionsMenu方法将不会被调用
		return true;
	}

	// updateUI此方法只能在handler中调
	@Override
	protected void updateUI(Object commandObject) {
		if (mPagingListViewDataCursorAdapter != null) {
			mPagingListViewDataCursorAdapter.notifyDataSetChanged();
		}
		SwitchUpdateUiCommand command = (SwitchUpdateUiCommand) commandObject;
		switch (command) {
		case INIT:
			fillPagingListViewData();
			fillPageNumSpinnerData();
			break;
		case RESET:
			fillPagingListViewData();
			fillPageNumSpinnerData();
			break;
		case CHANGE_PAGE:
			mPageNumSpinner.setSelection(currentPageNum);
			mPageNumSpinner.setSelected(false);
			fillPagingListViewData();
			break;
		case CHANGE_PAGE_CONTENT:
			fillPagingListViewData();
			break;
		default:
			break;
		}

	}

	/**
	 * Fill the list view.
	 */
	private void fillPagingListViewData() {

		startManagingCursor(mCursor);

		String[] from = new String[] { XtiebaPostsDb.TITLE };
		int[] to = new int[] { R.id.PostsRow_Title };

		mPagingListViewDataCursorAdapter = new PostsCursorAdapter(this,
				R.layout.posts_row, mCursor, from, to);
		lvPosts.setAdapter(mPagingListViewDataCursorAdapter);

		setAnimation();
	}

	private void fillPageNumSpinnerData() {
		LogUtlils.println("-----postsCount=" + postsCount);
		if (postsCount == 0) {
			mPageNumSpinner.setVisibility(View.GONE);
			PrePage.setVisibility(View.GONE);
			NextPage.setVisibility(View.GONE);
			lvPosts.setVisibility(View.GONE);
			postsTips.setText(R.string.postsEmpty);
			LogUtlils.println("loadingTips=" + loadingTips.getText());
			postsTips.setVisibility(View.VISIBLE);
			ToCrawlActivityBtn.setVisibility(View.VISIBLE);
			return;
		} else {
			mPageNumSpinner.setVisibility(View.VISIBLE);
			PrePage.setVisibility(View.VISIBLE);
			NextPage.setVisibility(View.VISIBLE);
			lvPosts.setVisibility(View.VISIBLE);
			postsTips.setVisibility(View.GONE);
			ToCrawlActivityBtn.setVisibility(View.GONE);
		}
		LogUtlils.println("Constants.PAGE_SIZE=" + Constants.PAGE_SIZE);
		LogUtlils.println("pageTotalNum=" + pageTotalNum);
		final String[] pageNums = new String[pageTotalNum];
		for (int i = 0; i < pageTotalNum; i++) {
			pageNums[i] = "第" + (i + 1) + "页";
		}
		// 将可选内容与ArrayAdapter连接
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, pageNums);
		// 设置下拉列表风格
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 将adapter添加到spinner中
		mPageNumSpinner.setAdapter(adapter);
		mPageNumSpinner.setSelection(currentPageNum);
		mPageNumSpinner.setSelected(false);
		// 添加Spinner事件监听
		mPageNumSpinner
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						if (mPageNumSpinner.isSelected()) {
							// 设置显示当前选择的项
							arg0.setVisibility(View.VISIBLE);
							currentPageNum = arg2;
							currentOffet = currentPageNum * Constants.PAGE_SIZE;
							getPagingListViewData(currentOffet,
									Constants.PAGE_SIZE,
									SwitchUpdateUiCommand.CHANGE_PAGE_CONTENT);
						}
						mPageNumSpinner.setSelected(true);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {

					}

				});
	}

	/**
	 * Set the view loading animation.
	 */
	private void setAnimation() {
		AnimationSet set = new AnimationSet(true);

		Animation animation = new AlphaAnimation(0.0f, 1.0f);
		animation.setDuration(600);
		set.addAnimation(animation);

		animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				-1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
		animation.setDuration(100);
		set.addAnimation(animation);

		LayoutAnimationController controller = new LayoutAnimationController(
				set, 0.5f);
		lvPosts.setLayoutAnimation(controller);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			super.isExit();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onStart() {
		if (mCursor != null) {
			startManagingCursor(mCursor);
		}
		getPagingListViewData(currentOffet, Constants.PAGE_SIZE,
				SwitchUpdateUiCommand.INIT);
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
//		startManagingCursor(mCursor);
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mProgressDialog != null) {
			mProgressDialog.dismiss();
		}
		stopManagingCursor(mCursor);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mCursor != null) {
			mCursor.close();
		}
		System.exit(0);
	}
}